#!/usr/bin/python
#  _*_coding:utf-8_*_

from urllib import parse
from urllib import request
import json
import threading
import time
import sys
import random
import re
import copy
import logging

import pprint

for arg in sys.argv:
    if(arg == 'yuemiao'):
        yuemiao_process = 1
    else:
        yuemiao_process = 0

config_f = open("./config.json")
config_data = json.load(config_f)


logger = logging.getLogger(__name__)
logging.basicConfig(level = logging.INFO,format = '[%(levelname)s]-%(funcName)s-line %(lineno)d:%(message)s')
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(levelname)s]-%(funcName)s-line %(lineno)d :%(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# ================================================== yuemiao config ========================================
linkman_id=config_data['yuemiao']['linkman_id']
seckill_id=config_data['yuemiao']['seckill_id']
id_card_num=config_data['yuemiao']['id_card_no']
tk=config_data['yuemiao']['tk']
yuemiao_cookie=config_data['yuemiao']['cookie']

# ================================================== jinniu config ========================================
hisId           =config_data['jinniu']['hisId']
platformSource  =config_data['jinniu']['platformSource']
platformId      =config_data['jinniu']['platformId']

deptId          =config_data['jinniu']['deptId']
doctorId        =config_data['jinniu']['doctorId']
scheduleId      =config_data['jinniu']['scheduleId']
scheduleDate    =config_data['jinniu']['scheduleDate']
visitPeriod     =config_data['jinniu']['visitPeriod']
visitBeginTime  =config_data['jinniu']['visitBeginTime']
visitEndTime    =config_data['jinniu']['visitEndTime']
patientId       =config_data['jinniu']['patientId']
jinniu_cookie   =config_data['jinniu']['cookie']

finish=0

def yuemiao_subcribe(th_id): # {
    global finish
    url="https://miaomiao.scmttec.com/seckill/seckill/subscribe.do?seckillId=%s&linkmanId=%s&idCardNo=%s&vaccineIndex=1"%(seckill_id, linkman_id,id_card_num) 
    header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
    'Cookie': yuemiao_cookie,
    'tk': tk,
    'X-Requested-With': 'XMLHttpRequest'
    }
    r=request.Request(url,headers=header)
    rsp=request.urlopen(r)
    data=rsp.read().decode('utf-8')
    #print(data)
    json_obj=json.loads(data)
    if(json_obj['ok'] != True):
        print(json_obj['msg'])
    else:
        finish = 1
        print("订购成功！！！")
    json_output=json.dumps(json_obj,indent=4, separators=(', ', ': '),ensure_ascii=False)
    if(th_id == 0) :
        print("=================================================== thread %d ==================================================\
                \n%s\n%s"% (th_id, json_output, url)) 
    retry = 0
    while (json_obj['ok'] != True) and (finish == 0):
        r=request.Request(url,headers=header)
        try:
            rsp=request.urlopen(r)
        except urllib.URLError as e:
            print(e)
        data=rsp.read().decode('utf-8')
        #print(data)
        json_obj=json.loads(data)
        if(json_obj['ok'] != True):
            #print(json_obj['msg'])
            logger.info("yuemiao msg: %s" %json_obj['msg'])
        else:
            finish = 1
            logger.info("订购成功！！")
        if((retry % 10) == 0):
            #print("=================================================== thread %d ==================================================\
            #        \n%s\n%s"% (th_id, json_output, url)) 
            logger.info(" thread %d \n%s\n%s"% (th_id, json_output, url))
        retry = retry + 1
        time.sleep(random.random())
# }

def jinniu_order(th_id, individual_args): # {
    global finish

    url="https://mp.med.gzhc365.com/api/register/generatororder?hisId=%s&platformSource=%s&platformId=%s"%(hisId, platformSource, platformId) 
    header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
    'Cookie': jinniu_cookie,
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }

    datas={
        "deptId":         deptId,
        "scheduleId":     individual_args['scheduleId'],
        "doctorId":       individual_args['doctorId'],
        "scheduleDate":   individual_args['scheduleDate'],
        "visitPeriod":    "",
        "visitBeginTime": individual_args['visitBeginTime'],
        "visitEndTime":   individual_args['visitEndTime'],
        "patientId":      patientId
        }
    if 'extFields' in individual_args.keys():
        datas['extFields'] = individual_args['extFields']

    datas=parse.urlencode(datas).encode('utf-8')
    r=request.Request(url,headers=header, data=datas)
    rsp=request.urlopen(r)
    data=rsp.read().decode('utf-8')
    #print(data)
    json_obj=json.loads(data)
    json_output=json.dumps(json_obj,indent=4, separators=(', ', ': '),ensure_ascii=False)
    if(th_id == 0) :
        #print("=================================================== thread %d ==================================================\
        #        \n%s\n%s"% (th_id, json_output, url)) 
        logger.info(" thread %d \n%s\n%s"% (th_id, json_output, url))
    retry = 0
    while (json_obj['code'] != -1):
        try:
            rsp=request.urlopen(r)
        except urllib.URLError as e:
            print(e)
        data=rsp.read().decode('utf-8')
        #print(data)
        json_obj=json.loads(data)
        retry = retry + 1
        if((retry % 10) == 0):
            #print("=================================================== thread %d ==================================================\
            #        \n%s\n%s"% (th_id, json_output, url)) 
            logger.info(" thread %d \n%s\n%s"% (th_id, json_output, url))
        time.sleep(random.random())
    finish = 1

#}

def get_dateschedule(): #{
    url = "https://mp.med.gzhc365.com/api/register/dateschedulelist?_route=h2153&hisId=2153&platformSource=1&platformId=2153"
    header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
    'Cookie': jinniu_cookie,
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    datas={
        "deptId":         deptId,
        }
    datas=parse.urlencode(datas).encode('utf-8')
    r=request.Request(url,headers=header, data=datas)
    rsp=request.urlopen(r)
    data=rsp.read().decode('utf-8')
    #print(data)
    json_obj=json.loads(data)
    json_output=json.dumps(json_obj,indent=4, separators=(', ', ': '),ensure_ascii=False)
    #print("=================================================== 日期列表  ==================================================\
    #        \n%s\n%s"% (json_output, url)) 
    logger.info(" 日期列表 \n\n%s\n%s"% (json_output, url))
    return json_obj
#}

def get_doctor_lst(schedule_date): #{
    url = "https://mp.med.gzhc365.com/api/register/scheduledoctorlist?_route=h2153&hisId=2153&platformSource=1&platformId=2153"
    header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
    'Cookie': jinniu_cookie,
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    datas={
        "deptId":         deptId,
        "scheduleDate": schedule_date
        }
    datas=parse.urlencode(datas).encode('utf-8')
    r=request.Request(url,headers=header, data=datas)
    rsp=request.urlopen(r)
    data=rsp.read().decode('utf-8')
    #print(data)
    json_obj=json.loads(data)
    json_output=json.dumps(json_obj,indent=4, separators=(', ', ': '),ensure_ascii=False)
    #print("=================================================== %s 医生列表  ==================================================\
    #        \n%s\n%s"% (schedule_date,json_output, url)) 
    logger.debug(" %s 医生列表 \n%s\n%s"% (schedule_date,json_output, url))
    return json_obj
#}


def get_schedule_lst(doctor_date_remark_id): #{
    url = "https://mp.med.gzhc365.com/api/register/schedulelist?_route=h2153&hisId=2153&platformSource=1&platformId=2153"
    header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
    'Cookie': jinniu_cookie,
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    datas={
            "scheduleDate": doctor_date_remark_id['scheduleDate'],
            "deptId": deptId,
            "doctorId": doctor_date_remark_id['doctorId'],
            "inputData": doctor_date_remark_id['doctorRemark']
        }

    datas=parse.urlencode(datas).encode('utf-8')
    r=request.Request(url,headers=header, data=datas)
    rsp=request.urlopen(r)
    data=rsp.read().decode('utf-8')
    #print(data)
    json_obj=json.loads(data)
    json_output=json.dumps(json_obj,indent=4, separators=(', ', ': '),ensure_ascii=False)
    #print("=================================================== %s 时间段列表  ==================================================\
    #        \n%s\n%s"% (doctor_date_remark_id['scheduleDate'],json_output, url)) 
    logger.debug(" %s 时间段列表 \n%s\n%s"% (doctor_date_remark_id['scheduleDate'],json_output, url))
    return json_obj
#}

def get_whole_week_args(): #{
    #==========================================================================
    # step#1: get all date , get scheduleDate for step#2 
    #==========================================================================
    week_order_args=[]
    jinniu_date_schedule_json = get_dateschedule()    
    valid_date=""
    for date_schedule_lst in jinniu_date_schedule_json['data']['scheduleList']: #{
        day_order_args={}
        if(date_schedule_lst['status'] == "1"): #{
            valid_date = date_schedule_lst['scheduleDate']
            day_order_args['scheduleDate'] = valid_date
            #==========================================================================
            # step#2:get doctor lst , get doctorRemark, doctorId for step#3 
            #==========================================================================
            doctor_date_remark_id={}
            doctor_lst_json = get_doctor_lst(valid_date)
            for doctor in doctor_lst_json['data']['doctorList']: #{
                if re.search(r'郑迪', doctor['doctorName']) : #{
                    doctor_date_remark_id={
                            "scheduleDate": valid_date,
                            "doctorRemark":doctor['doctorRemark'],
                            "doctorId":doctor['doctorId']
                            }
                    day_order_args['doctorId']=doctor['doctorId']
                    #==========================================================================
                    # step#3:get schedule lst , get scheduleId, visitBeginTime, visitEndTime 
                    #==========================================================================
                    schedule_lst_json = get_schedule_lst(doctor_date_remark_id)
                    for schedule_lst in schedule_lst_json['data']['itemList']: #{
                        if (schedule_lst['status'] == 1): #{
                            day_order_args['scheduleId'] = schedule_lst['scheduleId']
                            day_order_args['visitBeginTime'] = schedule_lst['visitBeginTime']
                            day_order_args['visitEndTime'] = schedule_lst['visitEndTime']
                            if 'extFields' in schedule_lst.keys(): #{
                                day_order_args['extFields'] = copy.deepcopy(schedule_lst['extFields'])
                                day_order_args['extFields'] = day_order_args['extFields'][0:-2]+',"flags":857}' # used when order. may be fixed
                            elif 'extFields' in day_order_args.keys():
                                day_order_args.pop('extFields')
                            #}

                            
                            #==========================================================================
                            # step#4: finaly, get all order args in 1 day
                            #==========================================================================
                            week_order_args.append(copy.deepcopy(day_order_args))
                            logger.debug("[debug]week_order_args add, len is %d\ndata is:%s\n"%(len(week_order_args),pprint.pformat(day_order_args)))
                            #pprint.pprint(week_order_args)

                        #} end if schedule_lst
                    #}for schedule_lst
                    #logger.debug(pprint.pformat(week_order_args))       
                #} end if re.search

            #} end for doctor
        #} end if(date_schedule_lst
    #} end for date_schedule_lst

    #print(week_order_args)
    return week_order_args
#}

if "debug" in sys.argv:
    all_args = get_whole_week_args()
    logging.debug(pprint.pformat(all_args))
else:
    if(yuemiao_process): #{
        for i in range(20):
            th=threading.Thread(target=yuemiao_subcribe, args=(i,))
    else:
        all_args = get_whole_week_args()
        for i in range(20):
            th=threading.Thread(target=jinniu_order, args=(i,all_args[ i % (len(all_args)) ]))
            th.start()
    #}

    while finish != 1 :
        time.sleep(1)
    
    sys.exit()
